/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package modeloUploadImagenFull;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import org.apache.commons.fileupload.FileItemStream;

/**
 *
 * @author CEBALLOS
 */
public class FileUpload {

    private String bd = "studentdb";
    private String classfor = "com.mysql.jdbc.Driver";
    private String url = "jdbc:mysql://localhost/" + bd;
    private String usuario = "root";
    private String clave = "";

    private Connection con = null;
    private PreparedStatement pr = null;

    public static boolean ProcesarArchivo(String ruta, FileItemStream item, String cedula) {
        try {
            File f = new File(ruta + File.separator + "images");

            if (!f.exists()) {
                f.mkdir();
            }
            {
                //los metodos a continuacion permiten subir el archivo desde cualquier 
                //directorio. en windows funciona ok
                
                String KeyValue1 = cedula + "_" + item.getName();
                File savedFile = new File(f.getAbsolutePath() + File.separator + KeyValue1);
                FileOutputStream fos = new FileOutputStream(savedFile);
                InputStream is = item.openStream();
                int x = 0;
                byte[] b = new byte[1024];

                while ((x = is.read(b)) != -1) {
                    fos.write(b, 0, x);
                }
                fos.flush();
                fos.close();
                return true;
            }

        } catch (Exception e) {
        }

        return false;

    }

    public void ProcesarArchivosql(String ruta, FileItemStream item, int studentId) {

        String sql = "Insert into student values(?,?)";
        try {
           
            
             System.out.println("----- " + item.getName() + " --- Nombre de la img ---- ");

            String KeyValue = "";

            KeyValue = studentId + "_" + item.getName();
            System.out.println("----- " + KeyValue + " --- Nombre del KeyValue ---- ");
            
            File archivos = new File(ruta + File.separator + "images" + File.separator + KeyValue);

            //System.out.println("----- " + ruta + " ---- ");
           

            FileInputStream entrada = new FileInputStream(archivos);

            Class.forName(classfor);

            try {//modo de conexion a travez de recurso
                con = getRecurso().getConnection();
            } catch (NamingException ex) {
                Logger.getLogger(FileUpload.class.getName()).log(Level.SEVERE, null, ex);
            }
           // con = DriverManager.getConnection(url, usuario, clave);

            pr = con.prepareStatement(sql);
            pr.setInt(1, studentId);

            pr.setBinaryStream(2, entrada, (int) archivos.length());

            pr.executeUpdate();
             //return true;

            System.out.println("EXITO CREATE!!!!!");
        } catch (FileNotFoundException | ClassNotFoundException | SQLException e) {

            System.out.println("ACTUALIZANDO!!!!!");
            sql = "update student set foto=?, nombre_img=? where studentId=?";
            try {
                //File archivo = new File(ruta + File.separator + item);
                // File archivos= new File(ruta +item);
                
                 String KeyValue;
                KeyValue = studentId + "_" + item.getName();
                System.out.println("----- " + KeyValue + " --- Nombre del KeyValue ---- ");
                
                File archivos = new File(ruta + File.separator + "images" + File.separator + KeyValue);

                FileInputStream entrada = new FileInputStream(archivos);

                Class.forName(classfor);
                try {
                    con = getRecurso().getConnection();
                } catch (NamingException ex) {
                    Logger.getLogger(FileUpload.class.getName()).log(Level.SEVERE, null, ex);
                }
                //  con = DriverManager.getConnection(url, usuario, clave);

                pr = con.prepareStatement(sql);
                
               
                pr.setString(2, KeyValue);
                    
                
                pr.setInt(3, studentId);

                pr.setBinaryStream(1, entrada, (int) archivos.length());

                pr.executeUpdate();

                //  System.out.println("UPDATE!!!!!");
            } catch (ClassNotFoundException | SQLException | FileNotFoundException ec) {
                ec.printStackTrace();
                System.out.println("Exception!!! SQL");

            }
        }

    }

    private DataSource getRecurso() throws NamingException {
        Context c = new InitialContext();
        return (DataSource) c.lookup("java:comp/env/recurso");
    }

}
